主要分成以下四大類:
Mounting 有四個生命週期
Constructor
static getDerivedStateFromProps(nextProps, prevState)
自己沒用過這個方法,但官網表示:
render()
componentDidMount
利用 console.log() 印出生命週期
import React, { Component } from 'react';
class LifeCycle extends Component {
constructor(props) {
super(props);
this.state = {
test: 'aaaa',
}
console.log('Constructor');
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log('getDerivedStateFromProps');
// 回傳 null 表示 state 無異動
return null;
}
componentDidMount() {
console.log('componentDidMount');
}
render() {
console.log('render');
return (
<div>
LifeCycle Test
</div>
)
}
}
export default LifeCycle;
網頁呈現
有 Child Componet 的範例
import React, { Component } from 'react';
import ChildLifeCycle from './ChildLifeCycle';
class ParentLifeCycle extends Component {
constructor(props) {
super(props);
this.state = {
test: 'aaaa',
}
console.log('Parent Constructor');
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log('Parent getDerivedStateFromProps');
// 回傳 null 表示 state 無異動
return null;
}
componentDidMount() {
console.log('Parent componentDidMount');
}
render() {
console.log('Parent render');
return (
<div>
Parent LifeCycle
<ChildLifeCycle />
</div>
)
}
}
export default ParentLifeCycle
import React, { Component } from 'react';
class ChildLifeCycle extends Component {
constructor(props) {
super(props);
this.state = {
test: 'aaaa',
}
console.log('Child Constructor');
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log('Child getDerivedStateFromProps');
// 回傳 null 表示 state 無異動
return null;
}
componentDidMount() {
console.log('Child componentDidMount');
}
render() {
console.log('Child render');
return (
<div>
Child LifeCycle
</div>
)
}
}
export default ChildLifeCycle;
網頁呈現